package com.huiminpay.merchant.service.impl;

import com.huiminpay.merchant.common.cache.domain.BusinessException;
import com.huiminpay.merchant.common.cache.domain.CommonErrorCode;
import com.huiminpay.merchant.common.cache.domain.ErrorCode;
import com.huiminpay.merchant.service.SmsService;
import lombok.extern.log4j.Log4j2;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.http.*;
import org.springframework.stereotype.Service;
import org.springframework.web.client.RestClientException;
import org.springframework.web.client.RestTemplate;

import java.util.HashMap;
import java.util.Map;
//@RequestBody: json对象--->java对象
//@ResponseBody: java对象--->json对象
@Log4j2
@Service
public class SmsServiceImpl implements SmsService {
    @Autowired
    RestTemplate restTemplate ;
    @Value("${sms.url}")
    String  smsUrl;
    @Value("${sms.effectiveTime}")
    String effectiveTime;

    //发送验证码
    @Override
    public String getSmsCode(String phone) throws BusinessException {
        String url=smsUrl+"/generate?name=sms&effectiveTime="+effectiveTime;
        //创建Map封装手机号
        Map<String,String> payload = new HashMap<>();
        payload.put("mobile",phone);
        //创建HttpHeaders对象，用于封装请求头信息
        HttpHeaders headers = new HttpHeaders();
        headers.setContentType(MediaType.APPLICATION_JSON); //设置请求类型为json类型(application/json)
        //创建HttpEntity对象，封装请求头和请求数据
        HttpEntity<String> entity = new HttpEntity(payload,headers);
        //使用restTemplate发送请求: exchange方法
        ResponseEntity<Map> responseEntity = restTemplate.exchange(url, HttpMethod.POST, entity, Map.class);
        Map body = responseEntity.getBody();
        log.info("请求结果:{}",body);
        if(body==null || body.get("result")==null){
            throw new BusinessException(CommonErrorCode.E_100107);
        }
        Map<String,String> map = (Map)body.get("result");
        String key = map.get("key");
        log.info("验证码key:{}",key);
        return key;
    }

    //检验验证码
    @Override
    public void checkVerifiyCode(String verifiyKey, String verifiyCode) throws BusinessException {
        String url = smsUrl+"/verify?name=sms&verificationKey="+verifiyKey+"&verificationCode="+verifiyCode;
        ResponseEntity<Map> responseEntity = null;
        Map responseMap = null;
        try {
            responseEntity = restTemplate.exchange(url, HttpMethod.POST, HttpEntity.EMPTY, Map.class);
            responseMap = responseEntity.getBody();
            log.info("验证结果{}",responseMap);
        } catch (RestClientException e) {
            e.printStackTrace();
            throw new BusinessException(CommonErrorCode.E_100102);
        }
        if (responseMap == null || responseMap.get("result") == null || !(Boolean)responseMap.get("result")) {
            throw new BusinessException(CommonErrorCode.E_100102);
        }
    }
}
